package com.miaosha.rabbitmq;

import com.google.gson.Gson;

import com.miaosha.entity.MiaoShaGoods;
import com.miaosha.entity.Order;
import com.miaosha.entity.vo.OrderVo;
import com.miaosha.mapper.MiaoShaGoodsMapper;
import com.miaosha.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Slf4j
@Component
public class RabbitMQReceiver {


    @Resource
    private MiaoShaGoodsMapper miaoShaGoodsMapper;

    @Resource
    private OrderService orderService;

    @RabbitListener(queues = "order")
    public void receive(String message) {
        Gson gson = new Gson();
        OrderVo orderVo = gson.fromJson(message, OrderVo.class);

        MiaoShaGoods byId = miaoShaGoodsMapper.findById(orderVo.getMiaoShaGoodsId());
        // 添加订单
        Order order = new Order();
        order.setUserId(orderVo.getUserId());
        order.setGoodsId(byId.getGoodsId());
        order.setPrice(byId.getPrice());
        order.setMiaoShaGoodsId(byId.getId());
        // 设置为未支付状态
        order.setPayStatus(0);
        order.setNum(1);

        miaoShaGoodsMapper.reduceStock(orderVo.getMiaoShaGoodsId());
        orderService.save(order);
    }
}